package com.yangchoi.jetpackcompose.ui.widget.component

import android.graphics.Bitmap
import android.util.Log
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView

/**
 * webView封装
 * @param url h5地址
 * @param htmlData html字符串
 */
@Composable
fun WebView(url:String? = null,htmlData:String? = null){

    var progress by remember { mutableStateOf(0) }
    var isError by remember { mutableStateOf(false) }

    Column(modifier = Modifier.fillMaxWidth()) {
        if(progress != 100 && progress != 0 && !isError){
            LinearProgressIndicator(
                modifier = Modifier.fillMaxWidth().height(2.dp),
                progress = progress / 100f,
                color = Color.Black
            )
        }

        AndroidView(
            modifier = Modifier.fillMaxWidth(),
            factory = { context ->
                WebView(context).apply {
                    //开启 JavaScript
                    settings.javaScriptEnabled = true
                    //允许缩放
                    settings.setSupportZoom(true)
                    settings.builtInZoomControls = true
                    settings.displayZoomControls = false
                    //调整 WebView 的布局大小以适应屏幕内容
                    settings.useWideViewPort = true
                    settings.loadWithOverviewMode = true
                    //启用混合模式（即加载 HTTP 和 HTTPS 混合内容）
                    settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                    //设置 WebView 的缓存模式
                    settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK

                    webViewClient = object : WebViewClient() {
                        // 开始加载
                        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                            super.onPageStarted(view, url, favicon)
                            Log.e("WebViewAG","start:$url")
                            isError = false
                        }
                        // 加载结束
                        override fun onPageFinished(view: WebView?, url: String?) {
                            super.onPageFinished(view, url)
                            Log.e("WebViewAG","finish:$url")
                            if (!isError) {
                                progress = 100
                            }
                        }
                        //处理 WebView 的链接跳转事件
                        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
//                            view?.loadUrl(request?.url.toString())
                            return true
                        }
                        // webview加载出错
                        override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
                            super.onReceivedError(view, request, error)
                            // 加载出错时，隐藏进度条
                            Log.e("WebViewAG","error:$error  $request  $view")
                            progress = 0
                            isError = true
                        }
                    }
                    webChromeClient = object : WebChromeClient(){
                        override fun onProgressChanged(view: WebView?, newProgress: Int) {
                            super.onProgressChanged(view, newProgress)
                            // 更新进度条
                            if(!isError){
                                progress = newProgress
                            }
                        }
                    }
                    if (!url.isNullOrEmpty()){
                        loadUrl(url)
                    }
                    if (!htmlData.isNullOrEmpty()){
                        loadData(htmlData, "text/html", "UTF-8")
                    }
                }
            }
        )
    }
}